package comment

import (
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Core"
)

type Home struct {

}

func (this Home) Setup() {
	Core.SetRoute("GET:/article/comment", "[I]comment.Home.GetAction")
	Core.SetRoute("POST:/article/comment", "[I]comment.Home.PostAction")
	Core.SetFunc("CommentForm", this.CommentForm)
	Core.SetFunc("CommentList", this.CommentList)
	Core.SetFunc("CommentSidebar", this.CommentSidebar)
}

func (_ Home) GetAction(request *Core.HxRequest, response *Core.HxResponse) {
	if len(request.Param) < 4 || !request.IsAjax() {
		response.Status = 404
		return
	}
	id := request.Param[3]
	res := map[string]interface {}{"res":true}
	res["comment"] = GetList(id)
	response.Json(res)
}

func (_ Home) PostAction(request *Core.HxRequest, response *Core.HxResponse) {
	if len(request.Param) < 4 {
		response.Status = 400
		return
	}
	data := request.Input().All()
	data["article"] = request.Param[3]
	msg := validateCommentData(data)
	res := map[string]interface{}{"res":false}
	if msg != "" {
		res["msg"] = msg
		response.Json(res)
		return
	}
	comment := AddComment(data["article"], data)
	res["res"] = true
	res["comment"] = comment
	response.Json(res)
	return
}

func (_ Home) CommentForm(b *Core.HxBehavior) string {
	return b.Template().Render("comment/form.html")
}

func (_ Home) CommentList(b *Core.HxBehavior) string {
	t := b.Template()
	t.Js("js/template.js")
	return t.Render("comment/list.html")
}

func (_ Home) CommentSidebar(b *Core.HxBehavior) string {
	t := b.Template()
	t.Assign("RecentComments", RecentComments(4))
	return t.Render("comment/sidebar.html")
}
